﻿using SAP.BusinessOne.Mackinac.Generator.Razor;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace SAP.BusinessOne.Mackinac.Generator.Engine
{
    class MackinacEngine
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private MackinacEngine()
        {
            log.Info("Starting mackinac generator");
        }

        public static MackinacEngine Create()
        {
            return new MackinacEngine();
        }

        public void Transform(string assemblyPath)
        {
            //Transform(Assembly.LoadFile(assemblyPath));
            var builder = new MackinacBuilder();
            builder.PutTarget(Assembly.LoadFile(assemblyPath));

            var bag = builder.ToDynamicBag();

            Transform(bag, "Templates/mackinac.h.cshtml", "mackinac.h");
            Transform(bag, "Templates/mackinac.cpp.cshtml", "mackinac.cpp");
        }

        private void Transform(dynamic bag, string template, string localtion)
        {
            if (CompareChecksum((string)bag.Checksum, localtion))
            {
                log.InfoFormat("File {0} is up-to-date", localtion);
                return;
            }

            log.InfoFormat("Generating file {0}", localtion);

            var tpl = File.ReadAllText(template);
            var rs = SimpleRazorEngine.Parse(tpl, bag);
            File.WriteAllText(localtion, rs);

#if DEBUG
            Process.Start("notepad++", localtion);
#endif
        }

        private bool CompareChecksum(string sha1, string localtion)
        {
            if (!File.Exists(localtion))
                return false;

            var fs = File.ReadAllText(localtion);
            var m = Regex.Match(fs, "[0-9A-F]{40}");

            if (m.Success)
            {
                return sha1 == m.Value;
            }

            return false;
        }

    }

}
